package com.qianyu.core.api;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.qianyu.core.entity.bean.QqAccount;
import com.qianyu.core.entity.dto.api.ClaimQBActivityDto;
import com.qianyu.core.enumerate.ResultEnum;
import com.qianyu.core.exception.CacheException;
import com.qianyu.core.exception.CustomerException;
import com.qianyu.core.exception.ProxyException;
import com.qianyu.core.util.HttpKit;
import com.qianyu.core.util.Object2MapUtil;
import com.qianyu.core.util.TimeUtil;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class ApiCommon {
    private final String baseUrl = "http://121.196.203.170:9001";

    //请求申请url
    private final String applyQqUrl = "http://118.178.125.179:7203/raise/account/lend";
    //长效代理url
    private final String proxyUrl = "http://114.55.52.42:9001/ros/api/getComIp";

    //刷新缓存
    private final String refreshCacheUrl = "http://118.178.125.179:7203/v1/account/cache";

    //查询信用分
    private final String queryCommonCreditUrl = baseUrl + "/api/auth/activateCache/queryCommonCredit";
    //查询Q币
    private final String fetchCachedQbQuantityUrl = baseUrl + "/api/auth/activateCache/fetchCachedQbQuantity";
    //获取活动列表
    private final String fetchQBActivityListUrl = baseUrl + "/api/qq/game/fetchQBActivityList";

    //领取qb
    private final String claimQBActivityUrl = baseUrl + "/api/qq/game/claimQBActivity";

    /**
     * 申请qq（hjb接口）
     */
    public String applyQq(Integer num) {
        Map<String, String> map = new HashMap<>();
        map.put("app", "coin");
        map.put("num", String.valueOf(num));
        map.put("cache", "1");
        try {
            return HttpKit.post(applyQqUrl, map);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 刷新缓存
     */
    public String refreshCache(String qq, Integer index) {
        Map<String, String> map = new HashMap<>();
        map.put("from", "coin");
        map.put("type", String.valueOf(1));
        map.put("account", qq);
        try {
            if (index < 3) {
                String json = HttpKit.get(refreshCacheUrl, map);
                JSONObject jsonObject = JSONObject.parseObject(json);
                if (jsonObject.getInteger("code") == 0) {
                    return jsonObject.getJSONObject("data").getString("cache");
                }
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 请求长效代理
     *
     * @param account 账号
     */
    public QqAccount applyProxy(QqAccount account, Integer index) {
        Map<String, String> map = new HashMap<>();
        map.put("code", account.getProvince());
        map.put("token", "iy7Snkla24Adas");
        String data;
        try {
            if (index < 3) {
                String proxy = HttpKit.get(proxyUrl, map);
                JSONObject proxyObj = JSONObject.parseObject(proxy);
                data = proxyObj.getString("data");
                if (data == null) {
                    data = HttpKit.get(proxyUrl, map);
                }
                JSONObject proxyDataObj = JSONObject.parseObject(data);
                account.setProxy1(proxyDataObj.getString("ip") + "-" + proxyDataObj.getString("port") + "-" + proxyDataObj.getString("user") + "-" + proxyDataObj.getString("pass"));
                return account;
            }
            return account;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询信用分
     *
     * @param account
     */
    public void queryCommonCredit(QqAccount account, Integer index) {
        String proxy = account.getProxy1();
        String[] split = proxy.split("-");
        String result;

        Map<String, Object> map = new HashMap<>();
        map.put("data", account.getCache());
        map.put("ip", split[0]);
        map.put("port", split[1]);
        map.put("user", split[2]);
        map.put("pass", split[3]);
        try {
            result = HttpRequest.post(queryCommonCreditUrl).body(JSONObject.toJSONString(map)).execute().body();
            JSONObject jsonObject = circulate(result);
            JSONObject object = jsonObject.getJSONObject("data").getJSONObject("data");
            account.setCreditScore(object.getInteger("score"));
            account.setCreditScoreTime(TimeUtil.unixTime(new Date()));
            account.setStatus(1);
        } catch (CacheException e) {
            while (index < 3) {
                String cache = refreshCache(account.getQq(), index++);
                account.setCache(cache);
                queryCommonCredit(account, index);
            }
            account.setStatus(2);
            account.setRemark(e.getMessage());
        } catch (ProxyException e) {
            while (index < 3) {
                QqAccount proxy1 = applyProxy(account, index);
                fetchCachedQbQuantity(proxy1, index);
            }
            account.setStatus(2);
            account.setRemark(e.getMessage());
        } catch (Exception e) {
            account.setStatus(-1);
            account.setRemark("");
        }
    }


    /**
     * 刷新qb接口
     * @param account
     * @param index
     */

    public void fetchCachedQbQuantity(QqAccount account, Integer index) {
        String proxy = account.getProxy1();
        String[] split = proxy.split("-");
        String result;

        Map<String, Object> map = new HashMap<>();
        map.put("data", account.getCache());
        map.put("ip", split[0]);
        map.put("port", split[1]);
        map.put("user", split[2]);
        map.put("pass", split[3]);
        try {
            result = HttpRequest.post(fetchCachedQbQuantityUrl).body(JSONObject.toJSONString(map)).execute().body();
            JSONObject jsonObject = circulate(result);
            JSONObject object = jsonObject.getJSONObject("data");
            account.setQnum(account.getQnum().add(new BigDecimal(object.getInteger("qb_balance"))));
            account.setQbTime(TimeUtil.unixTime());
            account.setStatus(1);
        } catch (CacheException e) {
            while (index < 3) {
                String cache = refreshCache(account.getQq(), index++);
                account.setCache(cache);
                fetchCachedQbQuantity(account, index);
            }
            account.setStatus(2);
            account.setRemark(e.getMessage());
        } catch (ProxyException e) {
            while (index < 3) {
                QqAccount proxy1 = applyProxy(account, index);
                fetchCachedQbQuantity(proxy1, index);
            }

            account.setStatus(2);
            account.setRemark(e.getMessage());
        } catch (Exception e) {
            account.setStatus(-1);
            account.setRemark("");
        }
    }


    /**
     * 获取活动列表
     */
    public JSONObject fetchQBActivityList(String url) {
        Map<String, String> map = new HashMap<>();
        map.put("gameActivityUrl", url);
        try {
            String body = HttpRequest.post(fetchQBActivityListUrl).body(JSONObject.toJSONString(map)).execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject.getInteger("code") != 200) {
                throw new CustomerException("活动链接有误！");
            }
            return jsonObject.getJSONObject("data");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject claimQBActivity(ClaimQBActivityDto dto, String qq, Integer index) {
        String result = null;
        try {
            Map<String, Object> map = Object2MapUtil.bean2Map(dto);
            result = HttpRequest.post(claimQBActivityUrl).body(JSONObject.toJSONString(map)).execute().body();
            return circulate(result);
        } catch (CacheException e) {
            while (index < 3) {
                String cache = refreshCache(qq, index++);
                dto.setCache(cache);
                claimQBActivity(dto, qq, index);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return JSONObject.parseObject(result);
    }


    private JSONObject circulate(String result) {
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") != 200) {
            String message = jsonObject.getString("message");
            if (message.contains("缓存")) {
                throw new CacheException(ResultEnum.CACHE_EXCEPTION);
            }
            if (message.contains("无法建立") || message.contains("代理")) {
                throw new CacheException(ResultEnum.PROXY_EXCEPTION);
            }
        }
        return jsonObject;
    }

}
